from playwright.async_api import async_playwright

async def save_google_login_state():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()

        print("登录页面")
        # 1. 访问应用登录页
        await page.goto(
            "https://app.sensortower-china.com/users/sign_in?product=st&return_to_path=%2Ftop-charts%3Fcountry%3DCA%26category%3D0%26date%3D2025-09-01%26device%3Diphone%26os%3Dios&locale=zh-CN"
        )

        # 2. 点击谷歌登录按钮，并等待新页面
        async with context.expect_page() as new_page_info:
            await page.click('a.google-sign-in[href="/users/auth/google_oauth2"]')

        google_login_page = await new_page_info.value
        await google_login_page.wait_for_load_state()

        # 3. 在谷歌登录页面输入凭据
        print("请在打开的浏览器中完成谷歌登录...")

        # ⚠️ 安全警告：账号密码不要硬编码在代码中！建议用环境变量。
        google_username = "maifeng@jonlantech.com"
        google_password = "maihao1122"

        await google_login_page.fill("input[type='email']", google_username)
        await google_login_page.press("input[type='email']", "Enter")
        await google_login_page.fill("input[type='password']", google_password)
        await google_login_page.press("input[type='password']", "Enter")

        # 4. 等待登录成功并返回原页面
        await page.wait_for_url("https://app.sensortower-china.com/dashboard")

        # 5. 保存会话状态到文件
        await context.storage_state(path="google_login_state.json")
        print("✅ 谷歌登录状态已成功保存到 google_login_state.json 文件。")

        await browser.close()
